package com.zmc.common.utils;

import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author：zmc
 * @Date：2025/1/26 11:26
 */
public class MD5Utils {

    public static final Logger log = LoggerFactory.getLogger(MD5Utils.class);

    /**
     * MD5加密 通过将盐值和密码进行加密，进行混淆
     * 登录的时候就通过密码和数据库中的盐值进行拼接 进行MD5加密后的结果是否相同
     */
    public static String encrypt(String context, String salt) {
        try {
            // 获取一个MD5消息摘要实例
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            // 更新消息摘要，将输入的文本内容转换为字节数组并进行处理
            md5.update((context + salt).getBytes());
            //获取十六进制字符串形式的MD5摘要
            String password = new String(Hex.encode(md5.digest()));
            char[] cs = new char[48];
            for (int i = 0; i < 48; i += 3) {
                cs[i] = password.charAt(i / 3 * 2);
                char c = salt.charAt(i / 3);
                cs[i + 1] = c;
                cs[i + 2] = password.charAt(i / 3 * 2 + 1);
            }
            return new String(cs);
        } catch (NoSuchAlgorithmException e) {
            log.error("md5 加密数据异常", e);
        }
        return null;
    }

    /**
     * 校验密码是否正确
     */
    public static boolean verify(String password, String md5) {
        try {
            char[] cs1 = new char[32];
            char[] cs2 = new char[16];
            for (int i = 0; i < 48; i += 3) {
                cs1[i / 3 * 2] = md5.charAt(i);
                cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
                cs2[i / 3] = md5.charAt(i + 1);
            }
            String salt = new String(cs2);
            MessageDigest md5Verify = MessageDigest.getInstance("MD5");
            md5Verify.update((password + salt).getBytes());
            return  new String(Hex.encode(md5Verify.digest())).equals(new String(cs1));
        }catch (NoSuchAlgorithmException e) {
            log.error("md5 校验密码异常", e);
        }
        return false;

    }

    public static void main(String[] args){
        String pass = "123456";
        String salt = "14j4h4n5456k6k7m";
        System.out.println(MD5Utils.encrypt(pass, salt));
        System.out.println(MD5Utils.verify(pass, "911142dj18472hbc4afn465804fd5b36b1k5f62ek437b2mb"));
    }
}
